// pages/note/note.js
Page({
  data: {
    noteDetail: null,
    areaMap: ["日常生活", "学术", "人际交往"],
    imageUrls: []
  },

  onLoad(options) {
    const notenum = options.notenum;
    if (notenum) {
      this.loadNoteDetail(notenum);
      console.log('[获取的notenum]',notenum)
    } else {
      console.error('未获取到有效的 notenum 参数');
    }
  },

  // 加载笔记详情
  loadNoteDetail(notenum) {
    const that = this;
    const token = wx.getStorageSync('token');
    wx.request({
      url: `http://localhost:8848/Note/${notenum}`,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: res => {
        console.log('当前 Token:', wx.getStorageSync('token'));
        console.log('[接口响应]', res.data);
        if (res.statusCode === 200) {
          const note = res.data;
          // 处理图片
          const imageUrls = note.img ? note.img.split(',') : [];
          this.setData({
            noteDetail: note,
            imageUrls: imageUrls
          });
          console.log('当前图片数组:', this.data.imageUrls) // 检查数组长度和内容
        }
      }
    });
  },

  // 图片预览
  previewImage(e) {
    const current = e.currentTarget.dataset.src;
    wx.previewImage({
      current,
      urls: this.data.imageUrls
    });
  },

  goUpdate:function(e){
    let notenum = e.currentTarget.dataset.notenum;
    wx.navigateTo({
      url: `/pages/updateNote/updateNote?notenum=${notenum}`,
    })
  },

  delete() {
    const that = this;
    const token = wx.getStorageSync('token');
    const notenum = that.data.noteDetail.notenum;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这篇笔记吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `http://localhost:8848/Note/delete/${notenum}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success(res) {
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 1500,
                  complete() {
                    setTimeout(() => {
                      wx.navigateBack({ delta: 1 });
                    }, 1500);
                  }
                });
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'error'
                });
              }
            }
          });
        }
      }
    });
  },

  goBack(){
    wx.navigateBack({
      delta:1
    })
    }
})